/**
 * @file {cf_pol数model}
 */
 'use strict'

 const { DataTypes, Model, Op } = require('../../../azeroth').sequelize;
 const {flawFilterInitData} = require('../common/init_data');
 class FlawFilterPol extends Model { }

 /**
  * @desc 映射需要的字段 【源库的 部分字段 --> 目标库字段】
  */
  const initFlawFilterData = (sequelize_aim) => {
      FlawFilterPol.init(
          ...flawFilterInitData,
          {
              freezeTableName: true,
              sequelize: sequelize_aim,
              modelName: 'flaw_filter',
              timestamps: false
          }
      )
  }

  FlawFilterPol.getNewsFlawFilterInfoFromLineDb =  async (sequelize_aim, panelId) => {
      let sql = 'select * from flaw_filter where panel_id = ' + panelId;
      let res = await sequelize_aim.query(sql, { type: sequelize_aim.QueryTypes.SELECT });
      return res[0];
  }
  /**
   * 差最新的flawFilter的id
   * @param {*} sequelize_aim 
   */
  FlawFilterPol.getLatestFlawFilterId = async (sequelize_aim, flawFilterUid) => {
    let sql = null;
    // 第一次进的时候，这里FlawFIlter 也对应更新上一次可能没同步完的数据
    if (flawFilterUid) {
        sql = 'select min(id) as id from flaw_filter where panel_table_uid = ' + flawFilterUid;
        let res = await sequelize_aim.query(sql, { type: sequelize_aim.QueryTypes.SELECT });
        return res[0].id ? res[0].id - 1 : 0;
    } else {
        sql = 'select max(id) as id from flaw_filter';
        let res = await sequelize_aim.query(sql, { type: sequelize_aim.QueryTypes.SELECT });
        return res[0].id ? res[0].id : 0;
    }
  }
  /**
   * 缺陷的最新片的sheetId
   */
  FlawFilterPol.getMaxSheetIds = async (sequelize_source) => {
      let sql = 'select max(sheet_id) as sheet_id from flaw';
      let res = await sequelize_source.query(sql, { type: sequelize_source.QueryTypes.SELECT });
      return res[0].sheet_id;
  }
  /**
   * 查询原始库 缺陷分类信息
   * @param {Sequlize} sequelize_source
   * @param {String} panelId
   * @returns
   */
  FlawFilterPol.getFlawFilterInfoByPanelId = async (sequelize_source , queryStr) => {
      let query = typeof(queryStr) == 'string' ? `b.panel_id = "${queryStr}"` : `a.sheet_id = ${queryStr}`;

      let sql = 'select b.panel_id, b.sheet_id as panel_table_uid, a.class_id as flaw_class_type, a.ui_show_text as symbol, c.show, c.color, d.station_name, d.station_id ' +
      'from flaw a join pol_aoi b on a.sheet_id = b.sheet_id join flaw_type c on c.flawClassType = a.class_id join station d on a.camera_id = d.station_id where  ' + query;
      let res = await sequelize_source.query(sql, { type: sequelize_source.QueryTypes.SELECT });
      return res;
  }
 /**
  *上传到产线flaw_filter 表
  * @param {Object} data 转换后上传的数据对象 
  */
  FlawFilterPol.uploadPolInfo = async (data) => {
      let res = await FlawFilterPol.bulkCreate([...data], {
        updateOnDuplicate: ['flaw_class_type', 'show', 'flaw_count', 'symbol', 'color']
      });
      return res;
 }

 module.exports = {
    initFlawFilterData,
    FlawFilterPol
 };